<?php
error_reporting(E_ERROR);
class Admini_PurchaseController extends Uuch_ManageController {

    public function init() {
        parent::init();
        $this->appendCss('/css/home/warehouse.css')->appendCss('/js/boxy/css/boxy.css');
        $this->appendCss('/admins/css/common.css');
        $this->appendScript('/js/jquery.min.js');
        $this->appendScript('/js/jquery.validate.min.js')->appendScript('/js/messages_cn.js')
                ->appendScript('/js/uuch.js')->appendScript('/js/boxy/js/jquery.boxy.js');

        $this->appendCss('/admins/css/adminshare.css');
        $this->appendCss('/admins/css/cangku.css');
        $ordertype = $this->getSafeParam("ordertype");
        $orderSearch = new Application_Model_Filter_OrderSearch();
        $this->view->type = 'buyshop';
        $orderSearch->status = Application_Model_Order::STATUS_PAID; //代受理
        $this->view->countorder1 = Application_Model_Order::countorder($orderSearch);
        if ($ordertype) {
            $this->view->type = 'mybuyshop';
            $ordertype = Uuch_Util::getUserNikeName();
        }
        $orderSearch->myorder = $ordertype;
        $orderSearch->noRechangeStatus = Application_Model_Order::ReChange_Complete;
        $orderSearch->status = Application_Model_Order::STATUS_CONFRIM; //待下单
        $this->view->countorder2 = Application_Model_Order::countorder($orderSearch);
        $orderSearch->status = Application_Model_Order::STATUS_UNSEND; //待发货
        $this->view->countorder3 = Application_Model_Order::countorder($orderSearch);
        $orderSearch->status = Application_Model_Order::STATUS_SELLER_SENDED; //待入库
        $this->view->countorder4 = Application_Model_Order::countorder($orderSearch);
        $orderSearch->status = Application_Model_Order::STATUS_SUBSCRIBE; //预订
        $this->view->countorder6 = Application_Model_Order::countorder($orderSearch);
        $orderSearch->status = Application_Model_Order::STATUS_OUTTIME_UNSEND; //超期未发货
        $this->view->countorder31 = Application_Model_Order::countorder($orderSearch);
        $orderSearch->status = Application_Model_Order::STATUS_OUTTIME_INSTORE; //超期未收货
        $this->view->countorder41 = Application_Model_Order::countorder($orderSearch);
        $orderSearch->status = Application_Model_Order::STATUS_OUTTIME_FIN; //超期财务风险
        $this->view->countorder51 = Application_Model_Order::countorder($orderSearch);
        $orderSearch->status = Application_Model_Order::STATUS_CONFRIM; //自己受理的
        $orderSearch->myorder = $ordertype;
        if ($this->getSafeParam("myoder")) {
            $orderSearch->myorder = Uuch_Util::getUserNikeName();
        }
        $this->view->countorder21 = Application_Model_Order::countorder($orderSearch);
        $orderSearch->status = "";
        $orderSearch->problem = Application_Model_Order::Problem_Appear;
        $this->view->countorder71 = Application_Model_Order::countorder($orderSearch); //自己受理的代购待用户回复的问题代购
        $orderSearch->problem = Application_Model_Order::Problem_User;
        $this->view->countorder711 = Application_Model_Order::countorder($orderSearch); //自己受理的代购用户已回复的问题代购
        $orderSearch->myorder = $ordertype;
        $this->view->countorder771 = Application_Model_Order::countorder($orderSearch); //所有用户已回复的问题代购
        $orderSearch->problem = Application_Model_Order::Problem_Appear;
        $this->view->countorder77 = Application_Model_Order::countorder($orderSearch); //所有待用户回复的问题代购
        $orderSearch->problem = "";
        $orderSearch->quickType = "rechangeStatus";
        $this->view->countorder810 = Application_Model_Order::countorder($orderSearch);
        $orderSearch->quickType = "";
        $orderSearch->rechangeStatus = Application_Model_Order::ReChange_Dispose;
        $this->view->countorder811 = Application_Model_Order::countorder($orderSearch);
        $orderSearch->rechangeStatus = Application_Model_Order::ReChange_Emit;
        $this->view->countorder812 = Application_Model_Order::countorder($orderSearch);
        $orderSearch->rechangeStatus = Application_Model_Order::ReChange_Seller;
        $this->view->countorder813 = Application_Model_Order::countorder($orderSearch);
        $orderSearch->rechangeStatus = Application_Model_Order::ReChange_Reissue;
        $this->view->countorder814 = Application_Model_Order::countorder($orderSearch);
        $orderSearch1 = new Application_Model_Filter_OrderSearch();
        $orderSearch1->starttime = date("Y-m-d");
        $this->view->countorder = Application_Model_Order::countorder($orderSearch1);
//        $this->vire->finOrder = Application_Model_Order::getFinOrder();
    }

    
    public function testinfoAction(){
        
       // $url = 'https://detail.tmall.com/item.htm?id=35733000897&ali_refid=a3_430676_1006:1105024738:N:脱毛器:83aa9f2842aca0b2fed88dfe3ac4c3aa&ali_trackid=1_83aa9f2842aca0b2fed88dfe3ac4c3aa&spm=a231o.7712113.1004.1.TscwxG';
       //   //$reader = Uuch_Reader_TaobaoReader::getInfo($url);
       //   $reader = new Uuch_Reader_TaobaoReaderxrh();
       //   $product = $reader->getTopUrl('女士剃毛器女用脱毛器腋下充电动仪私处脱毛机刮腋毛阴毛刮毛刀男',$url);
       //   //$product = $reader->getInfo($url);
       //   var_dump($product);

    }
    
    public function indexAction() {
        $this->setTitle("代购管理");
        $pagesize = $this->getSafeParam("pagesize");
        $pagesize = $pagesize ? $pagesize : 10;
        $pageindex = $this->getSafeParam('start');
        if (!$pageindex) {
            $pageindex = 0;
        }
        $quick = $this->getSafeParam('quick');
        $starttime = $this->getSafeParam('starttime');
        $starttime = $starttime ? $starttime : date("Y-m-d", mktime(0, 0, 0, date("m"), date("d"), date("Y") - 1));
        $endtime = $this->getSafeParam('endtime');
        $endtime = $endtime ? $endtime : date("Y-m-d");
        $status = $this->getSafeParam('status');
        $stus = $this->getSafeParam('stus');
        $day = $this->getSafeParam("day");
        $single = $this->getSafeParam("single");
        $isdelete = $this->getSafeParam("isdelete");
        $stype = 99;
        $myorder = $this->getSafeParam("myorder");
        $problem = $this->getSafeParam("problem");
        $abnormal = $this->getSafeParam("abnormal");
        $seltime = $this->getSafeParam("seltime");
        $seltime = $seltime ? $seltime : "createdTime";
        $taobaoid = $this->getSafeParam("taobaoid");
        $taobaoname = $this->getSafeParam("taobaoname");
        $operatorname = $this->getSafeParam("operatorname");
        $quickType = $this->getSafeParam("quickType");
        $rechangeStatus = $this->getSafeParam("rechangeStatus");
        $ordertype = $this->getSafeParam("ordertype");
        if ($stus != '') {
            $status = $stus;
            $stype = $stus;
        }
        if ($day == 1) {
            $stype = 100;
        }
        if ($quickType == "rechangeStatus") {
            $stype = 810;
        }
        if ($rechangeStatus == Application_Model_Order::ReChange_Dispose) {
            $stype = 811;
        } else if ($rechangeStatus == Application_Model_Order::ReChange_Emit) {
            $stype = 812;
        } else if ($rechangeStatus == Application_Model_Order::ReChange_Seller) {
            $stype = 813;
        } else if ($rechangeStatus == Application_Model_Order::ReChange_Reissue) {
            $stype = 814;
        }
        if ($myorder == 1) {
            $stype = 21;
            $myorder = Uuch_Util::getUserNikeName();
            if ($problem == 1) {
                $stype = 71;
            } else if ($problem == 2) {
                $stype = 711;
            }
        } else {
            if ($problem == 1) {
                $stype = 77;
            } else if ($problem == 2) {
                $stype = 771;
            }
        }
        if ($isdelete == 1) {
            $stype = 66;
        }
        if ($operatorname != "") {
            $myorder = $operatorname;
        }
        $myorder = $ordertype ? Uuch_Util::getUserNikeName() : $myorder;
        $orderSearch = new Application_Model_Filter_OrderSearch();
        $orderSearch->quick = $quick;
        $orderSearch->starttime = $starttime;
        $orderSearch->endtime = $endtime;
        $orderSearch->status = $status;
        $orderSearch->day = $day;
        $orderSearch->myorder = $myorder;
        $orderSearch->single = $single;
        $orderSearch->problem = $problem;
        $orderSearch->isdelete = $isdelete;
        $orderSearch->seltime = $seltime;
        $orderSearch->taobaoid = $taobaoid;
        $orderSearch->abnormal = $abnormal;
        $orderSearch->quickType = $quickType;
        $orderSearch->rechangeStatus = $rechangeStatus;
        $orderSearch->noRechangeStatus = Application_Model_Order::ReChange_Complete;
        $result = Application_Model_Order::getByPages($orderSearch, $pagesize, $pageindex);

        $paypalOrder=Application_Model_PaypalRisk::getPaypalOrder($result);
        $this->view->OrderPay=$paypalOrder;
        $uid=array();
        foreach($result['list'] as $item){
            $paypalBill=Application_Model_PayBill::getCardBill($item->userId,$item->id,Application_Model_PayBill::TYPE_ORDER);
            if($paypalBill){
                $datepid=strtotime($paypalBill[0]->dateCreated)+60*60*24;
                if($datepid > time()){
                    $uid[]=$item->userId;
                }
            }
        }
        $this->view->paypalBill=$uid;

        $this->view->result = $result;
        $this->view->buydetail = $result['list'];
        $this->view->quick = $quick;
        $this->view->starttime = $starttime;
        $this->view->endtime = $endtime;
        $this->view->status = $status;
        $this->view->arrsta = Application_Model_Order::getStatusList();
        $this->view->taobaoAll = Application_Model_Taobaoapi::byUserAll();
        $this->view->adminuserAll = Application_Model_adminuser::getAll();
        $this->view->day = $day;
        $this->view->myorder = $myorder;
        $this->view->stype = $stype;
        $this->view->single = $single;
        $this->view->problem = $problem;
        $this->view->abnormal = $abnormal;
        $this->view->isdelete = $isdelete;
        $this->view->seltime = $seltime;
        $this->view->taobaoid = $taobaoid;
        $this->view->taobaoname = $taobaoname;
        $this->view->pagesize = $pagesize;
        $this->view->operatorname = $operatorname;
        $this->view->expresscomp = Application_Model_shipType::getAll('word');
        $this->view->userVisible = Application_Model_Tracking::getUserVisibleAll();
        
    }

    /**
     * 订单详情
     */
    public function buydetailAction() {
        $this->setTitle("代购详情");
        $this->appendCss('/admins/css/yundan.css');
        $id = $this->_getParam('id');
        $result = Application_Model_Order::load($id);
        $this->view->statusAll = Application_Model_Order::getStatusAll();
        $this->view->order = $result;
        $this->view->expresscomp = Application_Model_shipType::getAll('word');
        $this->view->tracklog = Application_Model_Tracking::getAllByObjectTypeId(Application_Model_DomainobjectType::ObjectType_Order, $id);
        $this->view->checkMoneyAll = Application_Model_FinancialCheckItem::getMoneyTypeAll();
        $this->view->userVisible = Application_Model_Tracking::getUserVisibleAll();
    }

    /**
     * 受理
     */
    public function setconfrimAction() {
        $id = $this->getSafeParam("id");
        //$id = 144865;
        $orderItem = Application_Model_Order::load($id);
        if ($orderItem && $orderItem->status == Application_Model_Order::STATUS_PAID) {
            $orderItem->SetConfrim(Uuch_Util::getUserNikeName());
            $this->json(1);
        } else {
            $this->json(0);
        }
    }

    /**
     * 一键受理
     */
    public function setconfrimallAction() {
        $ids = $this->getSafeParam("ids");
        //$ids = '144865,145178,';
        $ids = rtrim($ids, ",");
        $ids = explode(',', $ids);
        //var_dump($ids);
        if($ids){
            foreach ($ids as $k => $id) {
                $orderItem = Application_Model_Order::load($id);
                if ($orderItem && $orderItem->status == Application_Model_Order::STATUS_PAID) {
                    $orderItem->SetConfrim(Uuch_Util::getUserNikeName());
                }
            }
            $this->json(1);
        }else{
            $this->json(0);
        }
        //exit;
    }  

    /**
     *  详情页下单
     */
    public function setprocureAction() {
        $id = $this->getSafeParam('id');
        $procureNo = $this->getSafeParam("procureNo");
        if ($procureNo == "") {
            $this->json(4);
            return;
        }
        $isTrue = Application_Model_Order::getIsTrueByIdProcureNo($id, $procureNo);
        if ($isTrue) {
            $this->json(2); //订单号已存在
            return;
        }
        $obj = Application_Model_Order::load($id);
        if ($obj->procureNo == "") {
            if ($obj->operator != Uuch_Util::getUserNikeName()) {
                $this->json(3); //操作人不对
                return;
            }
        }
        $obj->procureNo = $procureNo;
        $obj->status = Application_Model_Order::STATUS_UNSEND;
        $obj->dateConfrim = date("Y-m-d H:i:s");
        $obj->save();
        Application_Model_Tracking::addTrack(Application_Model_DomainobjectType::ObjectType_Order, $obj->id, $obj->operator, $obj->getStatusNames(), Application_Model_Tracking::User_None, $obj->status, date("Y-m-d H:i:s"));
        $this->json(1);
    }

    /**
     * 列表页下单
     */
    public function setwaitshipAction() {
        $id = $this->getSafeParam("id");
        $orderItem = Application_Model_Order::load($id);
        $operator = Uuch_Util::getUserNikeName();
        if ($orderItem && $orderItem->status == Application_Model_Order::STATUS_CONFRIM) {
            if ($orderItem->operator != $operator) {
                $this->json(9);
                return;
            }
            $result = $orderItem->SetWaitShip();
            $money = $orderItem->sum;
            $accountObj = Application_Model_UserAccount::load($orderItem->userId);
            $data = array('beforeMoney' => $accountObj->money, 'account' => $accountObj, 'afterMoney' => $accountObj->money, 'businessType' => "spzz");
            $data['trader'] = 'backend-account-cr';
            $this->_addFinance($orderItem, $money, $data);
            $data['trader'] = 'seller-number-dr';
            $this->_addFinance($orderItem, $money, $data);
            $this->json($result);
            return;
        }
        $this->json(0);
    }

    /**
     * 更新订单号或物流信息
     */
    public function updatelogisticsAction() {
        $id = $this->getSafeParam('id');                           //订单号
        $procureNo = $this->getSafeParam("procureNo");                 //淘宝号
        $logistics = $this->getSafeParam("logistics");             //物流公司
        $logisticsNo = $this->getSafeParam("logisticsNo");          //物流号
        $orderItem = Application_Model_Order::load($id);
        if (!$orderItem) {
            $this->json(0);
            return;
        }
        if ($orderItem->operator != Uuch_Util::getUserNikeName()) {
            $this->json(9);
            return;
        }
        if ($logisticsNo == "") {
            $result = $orderItem->UpdateProcureNo($procureNo);
            $this->json($result);
            return;
        }
        $result = $orderItem->UpdateLogistics($procureNo, $logistics, $logisticsNo);
        $this->json($result);
    }

    /**
     * 列表页卖家已发货
     */
    public function setsellerAction() {
        $id = $this->getSafeParam("id");
        $orderItem = Application_Model_Order::load($id);
        if (!$orderItem) {
            $this->json(0);
            return;
        }
        if ($orderItem->operator != Uuch_Util::getUserNikeName()) {
            $this->json(9);
            return;
        }
        $result = $orderItem->SetSeller();
        $this->json($result);
    }

    /**
     * 详情页卖家已发货
     */
    public function setlogisticsAction() {
        $id = $this->getSafeParam("id");
        $logistics = $this->_getParam("logistics");             //物流公司
        $logisticsNo = $this->_getParam("logisticsNo");          //物流号

        if ($logisticsNo == "") {
            $this->json(4);
            return;
        }
        $orderItem = Application_Model_Order::bylogistics($logisticsNo);
        if ($orderItem && $orderItem->id != $id) {
            $this->json(2);
            return;
        }
        $obj = Application_Model_Order::load($id);
        if ($obj->procureNo == "") {
            if ($obj->operator != Uuch_Util::getUserNikeName()) {
                $this->json(3);
                return;
            }
        }
        $obj->logistics = $logistics;
        $obj->logisticsNo = $logisticsNo;
        $obj->status = Application_Model_Order::STATUS_SELLER_SENDED;
        $obj->dateConfrim = date("Y-m-d H:i:s");
        $obj->save();
        Application_Model_Tracking::addTrack(Application_Model_DomainobjectType::ObjectType_Order, $obj->id, $obj->operator, $obj->getStatusNames(), Application_Model_Tracking::User_None, $obj->status, date("Y-m-d H:i:s"));
        $this->json(1);
        return;
    }

    public function setinstoreAction() {
        $id = $this->getSafeParam("id");
        $orderItem = Application_Model_Order::load($id);
        if (!$orderItem) {
            $this->json(0);
            return;
        }
        $operator = Uuch_Util::getUserNikeName();
        $result = $orderItem->SetInStore($operator);
        $this->json($result);
    }

    /**
     * 获取物流跟踪信息
     */
    public function getingexpressAction() {
        $id = $this->getSafeParam('id');
        $order = Application_Model_Order::load($id);
        $name = $order->Emmis->Name;
        $no = $order->logisticsNo;
        $cemskind = mb_convert_encoding(urldecode($name), 'GB2312', 'UTF-8');
        $cemskind = urlencode($cemskind);
        $niuMen = new Uuch_Express_NiuMen($cemskind, $no);
        $content = $niuMen->getTrackData();
        $this->json(array('content' => $content));
    }

    public function agentAction() {
        $this->setTitle('后台：生成代购订单');
        $this->appendCss('/css/daigou/fill.css');
        if (!$this->isPost()) {
            return;
        }

        $form = new Application_Form_PurchaseAgent();
        if (!$form->isValid($this->getRequest()->getPost())) {
            return;
        }

        $sku = $form->getValue('sku');
        if ($sku == null) {
            $sku = $form->getValue('url');
        }

        $values = $form->getValues();
        $product = Application_Model_Product::getByUrl($this->_getParam('url'));
        if (null == $product) {
            $product = new Application_Model_Product();
        }

        if ($product->Sku != $sku) {
            $product->Id = NULL;
            $product->Image = $form->getValue('image');
        }
        $product->setOptions($values);

        $product->RemoteImage = $form->getValue('image');
        $product->ShipFee = $form->getValue('shipFee');
        $product->Sku = $sku;
        $product->PropertyAlias = $this->getSafeParam('prop');
        $product->save();

        $comm = $this->getSafeParam('comment');
        $cart = Application_Model_Cart::current();
        $cart->addCartItem($product, $form->getValue('quantity'), "悠奇后台发起的代购!" . $comm);

        $this->_helper->redirector('cart');
    }

    public function cartAction() {
        $this->appendCss('/css/daigou/fill.css');

        $this->view->cart = Application_Model_Cart::current();
        $this->view->title = '后台：购物车';
    }

    /**
     * 结算页
     */
    public function checkoutAction() {
        $cart = Application_Model_Cart::current();
        $user = Application_Model_User::getByStoreNo($this->getSafeParam('storeno'));
        $couponArr = array();
        foreach ($cart->getShops(true) as $shop) {
            $couponArr[$shop->Id]["couponNo"] = '0';
            $couponArr[$shop->Id]["password"] = '';
        }
        $orders = $cart->createOrders($couponArr);

        if ($user == NULL) {
            $this->error('没有找到对应的用户，请检查仓库号');
            return;
        }

//        var_dump($orders);exit;
        $needMoney = $this->getSafeParam('needmoney') == 'true';
        if ($needMoney) {
            $orderSum = Uuch_List::create($orders)->sum(function($item) {
                return $item->Sum;
            });
            if ($orderSum > $user->Account->Money) {
                $this->error('用户余额不足，生成代购订单失败');
                return;
            }
        }
        $operator = Uuch_Util::getUserNikeName();
        foreach ($orders as $resultVal) {
            $order = $resultVal['order'];
            $order->UserId = $user->Id;
            if (!$needMoney) {
                $order->Status = Application_Model_Order::STATUS_PAID;
                $order->datePaid = $this->now();
            }
            $order->save();
            Application_Model_Tracking::addTrack(Application_Model_DomainobjectType::ObjectType_Order, $order->Id, $operator, "后台手工添加代购", Application_Model_Tracking::User_Block, "", date("Y-m-d H:i:s"));
            if ($needMoney) {
                $user->Account->Pay($order->Sum, $order);
            }
            Application_Model_Operate::addOperate($order->Sum, null, $order->Id, '后台申请新代购订单', $user->Id);
        }

        $cart->clear();
        $this->message('生成代购订单成功');
    }

    public function changeitemAction() {
        $request = $this->getRequest();
        $itemid = $request->getParam('itemid');
        $quantity = $request->getParam('quantity');
        $comment = $request->getParam('comment');
        $selected = $request->getParam('selected');
        $item = Application_Model_CartItem::load($itemid);
        $item->Quantity = $quantity;
        $item->Comment = $comment;
        $item->IsSelected = $selected;
        $item->save();
        $this->json(TRUE);
    }

    /**
     * 获取订单预订时间
     */
    public function getreserveorderAction() {
        $orderId = $this->getSafeParam("id");
        $orderItem = Application_Model_Order::load($orderId);
        if ($orderItem) {
            $this->json(array("reserveTime" => $orderItem->dateShip));
            return;
        }
        $this->json();
    }

    /**
     * 订单预订
     */
    public function setreserveorderAction() {
        $orderId = $this->getSafeParam("id");
        $reserveTime = $this->getSafeParam("reserveTime");
        $reserveCause = $this->getSafeParam("reserveCause");
        $orderItem = Application_Model_Order::load($orderId);
        if ($orderItem->Operator != Uuch_Util::getUserNikeName()) {
            $this->json(9);
            return;
        }
        $result = $orderItem->setReserveOrder($reserveTime, $reserveCause);
        $this->json($result);
    }

    /**
     * 修改状态
     */
    public function editinteriorAction() {
        $orderId = $this->getSafeParam("id");
        $status = $this->getSafeParam("status");
        $operator = Uuch_Util::getUserNikeName();
        $orderItem = Application_Model_Order::load($orderId);
        if ($orderItem->Operator != $operator) {
            $this->json(9);
            return;
        }
        $result = $orderItem->editInterior($status, $operator);
        $this->json($result);
    }

    /**
     * 取消退款
     */
    public function cancelAction() {
        $orderId = $this->getSafeParam("id");
        $operator = Uuch_Util::getUserNikeName();
        $orderItem = Application_Model_Order::load($orderId);
        if ($orderItem->Operator != $operator) {
            $this->json(array("type" => 9));
            return;
        }
        $accountObj = Application_Model_UserAccount::load($orderItem->userId);
        $beforeMoney = $accountObj->Money;
        $items = $orderItem->getItems();
        $money = 0;
        foreach ($items as $item) {
            if ($item->status == 1) {
                continue;
            }
            $money += ($item->price * $item->quantity);
        }
        $shipFee = $orderItem->shipFee;
        $result = $orderItem->Cancel($operator);
        if (is_array($result)) {

            $params = array('beforeMoney' => $beforeMoney, 'account' => $accountObj, 'afterMoney' => $beforeMoney + $money, 'businessType' => 'spjztk', 'trader' => 'account-number-dr');

            $this->_addFinance($orderItem, $money, $params);
            $params['trader'] = 'backend-account-cr';
            $params['beforeMoney'] = $params['afterMoney'];
            $this->_addFinance($orderItem, $money, $params);
            if ($shipFee) {
                $params['beforeMoney'] = $params['afterMoney'];
                $params['businessType'] = 'yftk';
                $params['trader'] = 'backend-account-cr';
                $this->_addFinance($orderItem, $shipFee, $params);
                $params['trader'] = 'account-number-dr';
                $params['beforeMoney'] = $params['afterMoney'];
                $params['afterMoney'] = $params['beforeMoney'] + $shipFee;
                $this->_addFinance($orderItem, $shipFee, $params);
            }
            $this->json(array("type" => 1, "result" => $result));
            return '';
        }
        $this->json(array("type" => $result));
    }

    /**
     * 单项退款
     */
    public function singlereturnAction() {
        $id = $this->getSafeParam("id");
        $singleId = $this->getSafeParam("singleId");

        $operator = Uuch_Util::getUserNikeName();
        $orderItem = Application_Model_Order::load($id);
        $accountObj = Application_Model_UserAccount::load($orderItem->userId);
        $beforeMoney = $accountObj->Money;
        if ($orderItem->Operator != $operator) {
            $this->json(9);
            return;
        }
        $result = $orderItem->singleReturn($singleId, $operator);
        $item = Application_Model_OrderItem::load($singleId);
        $money = $item->Price;
        $params = array('beforeMoney' => $beforeMoney, 'account' => $accountObj, 'afterMoney' => $beforeMoney + $money, 'businessType' => 'spjztk', 'trader' => 'account-number-dr', 'remark' => '单项付款');

        $this->_addFinance($orderItem, $money, $params);
        $params['trader'] = 'backend-account-cr';
        $params['beforeMoney'] = $params['afterMoney'];
        $this->_addFinance($orderItem, $money, $params);
        $this->json($result);
    }

    /**
     * 合并
     */
    public function mergerorderAction() {
        $itemList = $this->getSafeParam("itemlist");
        $arrItemId = explode(",", $itemList);
        if (count($arrItemId) == 2) {
            $this->json(4);
            return;
        }
        $operator = Uuch_Util::getUserNikeName();
        $orderItem = Application_Model_Order::load($arrItemId[0]);
        $result = $orderItem->MergerOrder($arrItemId, $operator);
        $this->json($result);
    }

    public function getiteminfoAction() {
        $orderId = $this->getSafeParam("orderId");
        $idlist = $this->getSafeParam("idlist");
        $orderItem = Application_Model_Order::load($orderId);
        if ($orderItem->Operator != Uuch_Util::getUserNikeName()) {
            $this->json(array("type" => 9));
            return;
        }
        $result = $orderItem->getItemInfo($idlist);
        if (is_array($result)) {
            $this->json(array("type" => 1, "result" => $result));
            return;
        }
        $this->json(array("type" => $result));
    }

    /**
     * 订单拆分
     */
    public function splitorderAction() {
        $orderId = $this->getSafeParam("id");
        $splitnum = $this->getSafeParam("splitnum");
        $orderItem = Application_Model_Order::load($orderId);
        if ($orderItem->Operator != Uuch_Util::getUserNikeName()) {
            $this->json(9);
            return;
        }
        $result = $orderItem->SplitOrder($splitnum);
        $this->json($result);
    }

    /**
     * 获取说明(comment)
     */
    public function getcommentAction() {
        $id = $this->getSafeParam('id');
        $obj = Application_Model_OrderItem::load($id);
        if ($obj) {
            $this->json($obj->description);
            return;
        }
        $this->json(" ");
    }

    /**
     *  设置说明
     */
    public function setcommentAction() {
        $orderItemId = $this->getSafeParam("orderId");
        $comment = $this->getSafeParam("comment");
        $operator = Uuch_Util::getUserNikeName();
        $orderItem = Application_Model_OrderItem::load($orderItemId);
        if (!$orderItem) {
            $this->json(0);
            return;
        }
        $orderItem->description = $comment;
        $orderItem->save();
        Application_Model_Tracking::addTrack(Application_Model_DomainobjectType::ObjectType_Order, $orderItem->OrderId, $operator, "订单中的商品" . mb_substr($orderItem->productName, 0, 8, 'utf-8') . "···添加备注。", Application_Model_Tracking::User_Block, "", date("Y-m-d H:i:s"));
        $this->json(1);
    }

    /**
     * 获取代购问题详情
     */
    public function problemshowAction() {
        $orderId = $this->getSafeParam("orderId");
        $problemItem = Application_Model_problem::byissue($orderId, Application_Model_problem::TYPE_ORDER);
        $arrProblem = array();
        if (!$problemItem) {
            $this->json(0);
            return;
        }
        foreach ($problemItem as $key => $pbVal) {
            $arrProblem[$key]["issueetype"] = $pbVal->Issuetype;
            $arrProblem[$key]["content"] = htmlspecialchars($pbVal->Content);
            $arrProblem[$key]["dateCreated"] = $pbVal->DateCreated;
            $arrProblem[$key]["userName"] = $pbVal->User->NikeName;
            $arrProblem[$key]["userId"] = $pbVal->Userid;
        }
        $this->json(array("type" => 1, "arrProblem" => $arrProblem));
    }

    /**
     * 设置问题详情
     */
    public function addproblemAction() {
        $orderId    = $this->getSafeParam("id");
        $content    = $this->getSafeParam("content");
        $repay      = $this->getRequest()->getParam('repay', 0);
        $money      = (float)$this->getRequest()->getParam('repaysum');
        $orderItem  = Application_Model_Order::load($orderId);
        
        if (!$orderItem) {
            $this->json(array("type" => 0));
            return;
        }
        if ($orderItem->Operator != Uuch_Util::getUserNikeName()) {
            $this->json(array("type" => 9));
            return;
        }
        if ($content == "") {
            $this->json(array("type" => 2));
        }
        if ($repay == 1 && $money > 0) {
            $type   = Application_Model_PayBill::TYPE_ORDER;//2
            $status = Application_Model_RepayLink::STATUS_CREATED;
            $old    = Application_Model_RepayLink::getByRelationIdTypeStatus($orderId, $type, $status);
            if ($old) {
                $old->delete(); 
            }                   
            $link = new Application_Model_RepayLink(array(
                    'name'          => '代购单号' . $orderItem->getOrderNum() . '补交款',
                    'description'   => '',
                    'type'          => $type,
                    'link'          => $orderItem->getOrderNum(),
                    'relationId'    => $orderId,
                    'repayMoney'    => $money
                ));
            $link->Status       =  $status;
            $link->DateCreated  =  date('Y-m-d H:i:s');
            $link->UserId       =  $orderItem->UserId;
            $link->save();
            $content .= '<h3>同意补款请点击<a href="http://www.uuch.com/pay/index/index/type/9/id/' . $link->Id . '">立即补款</a></h3>';
        }
        $result = $orderItem->addProblem($content);
        $this->json($result);
    }

    /**
     * 问题解决
     */
    public function solveproblemAction() {
        $id = $this->getSafeParam("id");
        $orderItem = Application_Model_Order::load($id);
        if (!$orderItem) {
            $this->json(0);
            return;
        }
        if ($orderItem->Operator != Uuch_Util::getUserNikeName()) {
            $this->json(9);
            return;
        }
        if ($orderItem->Problem != Application_Model_Order::Problem_Appear && $orderItem->Problem != Application_Model_Order::Problem_User) {
            $this->json(2);
            return;
        }
        $orderItem->Problem = Application_Model_Order::Problem_Complete;
        $orderItem->DateConfrim = date("Y-m-d H:i:s");
        $orderItem->save();
        Application_Model_Tracking::addTrack(Application_Model_DomainobjectType::ObjectType_Order, $orderItem->Id, $orderItem->Operator, "代购(" . $orderItem->getOrderNum() . ")问题解决.", Application_Model_Tracking::User_Block, "", date("Y-m-d H:i:s"));
        $this->json(1);
    }

    /**
     * 更改操作人
     */
    public function editoperatorAction() {
        $id = $this->getSafeParam("id");
        $orderItem = Application_Model_Order::load($id);
        if (!$orderItem) {
            $this->json(0);
            return;
        }
        $orderItem->Operator = Uuch_Util::getUserNikeName();
        $orderItem->DateConfrim = date("Y-m-d H:i:s");
        $orderItem->save();
        Application_Model_Tracking::addTrack(Application_Model_DomainobjectType::ObjectType_Order, $orderItem->Id, $orderItem->Operator, "代购(" . $orderItem->getOrderNum() . ")的操作人更改为：" . $orderItem->Operator, Application_Model_Tracking::User_None, "", date("Y-m-d H:i:s"));
        $this->json(1);
    }

    public function handworkshowAction() {
        $orderId = $this->getSafeParam("orderId");
        $checkItem = Application_Model_FinancialCheckItem::getAllbyObjectTypeObjectId(Application_Model_DomainobjectType::ObjectType_Order, $orderId);
        if (!$checkItem) {
            $this->json(array("type" => 0));
            return;
        }
        $arrCheck = array();
        foreach ($checkItem as $key => $checkVal) {
            $arrCheck[$key]["dateCreated"] = $checkVal->DateCreated;
            $arrCheck[$key]["reason"] = $checkVal->Reason;
            $arrCheck[$key]["applyName"] = $checkVal->ApplyName;
            $arrCheck[$key]["checkType"] = $checkVal->MoneyTypeName;
            $arrCheck[$key]["statusName"] = $checkVal->StatusName;
        }
        $this->json(array("type" => 1, "arrCheck" => $arrCheck));
    }

    public function operatelogAction() {
        $id = $this->getSafeParam("operatelog");
        $checkItem = Application_Model_Tracking::getAllByObjectTypeId(Application_Model_DomainobjectType::ObjectType_Order, $id);
        $arrCheck = array();
        foreach ($checkItem as $key => $checkVal) {
            $arrCheck[$key]["dateAdd"] = $checkVal->dateAdd;
            $arrCheck[$key]["operator"] = $checkVal->operator;
            $arrCheck[$key]["content"] = $checkVal->content;
            $arrCheck[$key]["IsUser"] = $checkVal->IsUser;
        }
        $this->json(array("type" => 1, "arrCheck" => $arrCheck, "name" => $id));
    }

    public function sethandworkAction() {
        $id = $this->getSafeParam("id");
        $hendworkType = $this->getSafeParam("hendworkType");
        $handworkMoney = $this->getSafeParam("handworkMoney");
        $handworkReason = $this->getSafeParam("handworkReason");
        $businessType = $this->getSafeParam("businessType");
        $orderItem = Application_Model_Order::load($id);
        if (!$orderItem) {
            $this->json(0);
            return;
        }
        $accountObj = Application_Model_UserAccount::load($orderItem->userId);
        $beforeMoney = $accountObj->Money;
        if ($orderItem->Status == Application_Model_Order::STATUS_PAYING || $orderItem->Status == Application_Model_Order::STATUS_CANCEL || $orderItem->isdelete == 1) {
            $this->json(4);
            return;
        }
        if ($hendworkType == Application_Model_FinancialCheckItem::Money_Need) {
            $userMoney = $orderItem->Userinfo->Account->Money;
            if ($userMoney < $handworkMoney) {
                $this->json(3);
                return;
            }
        }
//        if($orderItem->Operator != Uuch_Util::getUserNikeName()){
//            $this->json(9);
//            return ;
//        }
        $result = $orderItem->setHandWork($hendworkType, $handworkMoney, $handworkReason);
        $this->json($result);
        if (0 < $handworkMoney) {
            $data = array('beforeMoney' => $beforeMoney, 'account' => $accountObj, 'afterMoney' => $beforeMoney + $handworkMoney, 'businessType' => $businessType);
            if (1 == $hendworkType) {
                $data['afterMoney'] = $data['beforeMoney'] - $handworkMoney;
                $data['trader'] = 'account-number-cr';
                $this->_addFinance($orderItem, $handworkMoney, $data);
                $data['trader'] = 'backend-account-dr';
            } elseif (2 == $hendworkType) {
                $data['trader'] = 'account-number-dr';
                $this->_addFinance($orderItem, $handworkMoney, $data);
                $data['trader'] = 'backend-account-cr';
            }
            $data['beforeMoney'] = $data['afterMoney'];
            $this->_addFinance($orderItem, $handworkMoney, $data);
        }
    }

    /**
     *  显示异常信息
     */
    public function abnormalshowAction() {
        $id = $this->getSafeParam("orderId");
        $isType = $this->getSafeParam("isType");
        $orderItem = Application_Model_Order::load($id);
        if (!$orderItem) {
            $this->json(array("type" => 0));
            return;
        }
        $abnrmalOrder = Application_Model_QualityProblem::byObjectIdObjectType($id, Application_Model_DomainobjectType::ObjectType_Order);
        $orderAbnrmal = array();
        if ($abnrmalOrder) {
            $orderAbnrmal["id"] = $orderItem->Id;
            $orderAbnrmal["orderNum"] = $orderItem->OrderNum;
            $orderAbnrmal["SoleNo"] = $orderItem->SoleNo;
            $orderAbnrmal["arrAbnormal"] = $abnrmalOrder->getContentTrack();
        }
        $itemAbnormal = array();
        foreach ($orderItem->getItems() as $itemVal) {
            $abnrmalOrderItem = Application_Model_QualityProblem::byObjectIdObjectType($itemVal->Id, Application_Model_DomainobjectType::ObjectType_OrderItem);
            if (!$abnrmalOrderItem) {
                continue;
            }
            $productd = $itemVal->byproductd;
            $image = $productd->image ? $productd->image : $productd->remoteImage;
            $arrimage = explode('"', $image);
            if (count($arrimage) > 1) {
                $imgUrl = $arrimage[1];
            } else {
                $imgUrl = $image;
            }
            $itemAbnormal[$itemVal->Id]["id"] = $itemVal->Id;
            $itemAbnormal[$itemVal->Id]["name"] = $itemVal->ProductName;
            $itemAbnormal[$itemVal->Id]["alias"] = $productd->PropertyAlias;
            $itemAbnormal[$itemVal->Id]["problemContent"] = $itemVal->problemContent;
            $itemAbnormal[$itemVal->Id]["img"] = $imgUrl;
            $itemAbnormal[$itemVal->Id]["arrAbnormal"] = $abnrmalOrderItem->getContentTrack();
        }
        $lossUser = "";
        $lossLog = Application_Model_FinancialCheckItem::getOneByObjectMonetType(Application_Model_DomainobjectType::ObjectType_Order, $id, Application_Model_FinancialCheckItem::Money_Loss);
        if ($lossLog) {
            $lossUser = $lossLog->ApplyName;
        }
        $reChangItem = array();
        if ($isType == 1) {
            if ($orderItem->scheme != Application_Model_Order::Scheme_Reissue) {
                $reChangItem[Application_Model_Tracking::Type_Address] = $this->getReChangeItem($id, Application_Model_Tracking::Type_Address);
                $reChangItem[Application_Model_Tracking::Type_ReChangeLogistics] = $this->getReChangeItem($id, Application_Model_Tracking::Type_ReChangeLogistics);
                $reChangItem[Application_Model_Tracking::Type_ReChangeMoney] = $this->getReChangeItem($id, Application_Model_Tracking::Type_ReChangeMoney);
                $reChangItem[Application_Model_Tracking::Type_ReissueLogistics] = $this->getReChangeItem($id, Application_Model_Tracking::Type_ReissueLogistics);
                $reChangItem[Application_Model_Tracking::Type_ReturnMoney] = $this->getReChangeItem($id, Application_Model_Tracking::Type_ReturnMoney);
            }
            $reChangItem[Application_Model_Tracking::Type_ReissueLogistics] = $this->getReChangeItem($id, Application_Model_Tracking::Type_ReissueLogistics);
        }
        $this->json(array("type" => 1, "orderAbnrmal" => $orderAbnrmal, "itemAbnrmal" => $itemAbnormal, "abnormalType" => $orderItem->isAbnormal, "lossUser" => $lossUser, "reChangItem" => $reChangItem, "scheme" => $orderItem->scheme, "rechangeStatus" => $orderItem->rechangeStatus));
    }

    public function delproblemAction() {
        $abnormalId = $this->getSafeParam("abnormalId");
        $abnormalItem = Application_Model_QualityProblemContent::load($abnormalId);
        if (!$abnormalItem) {
            $this->json(array("status" => 0));
            return;
        }
        $problemId = $abnormalItem->ProblemId;
        $abnormalItem->getDelTrack();
        $abnormalItem->delete();
        $problemNum = Application_Model_QualityProblemContent::getNum($problemId, "");
        if ($problemNum == 0) {
            $problemItem = Application_Model_QualityProblem::load($problemId);
            $problemItem->delProblem();
            $problemItem->delete();
        }
        $this->json(array("status" => 1));
        return;
    }

    public function editqualityAction() {
        $qualityId = $this->getSafeParam("qualityId");
        $qualityItem = Application_Model_Tracking::load($qualityId);
        if (!$qualityItem) {
            $this->json(false);
            return;
        }
        $trackId = $qualityItem->id;
        $dateAdd = $qualityItem->dateAdd;
        $operator = $qualityItem->operator;
        $content = $qualityItem->content;
        $shipId = $qualityItem->shipId;
        $money = 0;
        if ($qualityItem->operateType == Application_Model_Tracking::Type_ReChangeLogistics) {
            $reChangeItem = Application_Model_Tracking::getOneByObjectTypeIdOperateType(Application_Model_DomainobjectType::ObjectType_Order, $qualityItem->objectId, Application_Model_Tracking::Type_ReChangeMoney);
            $money = $reChangeItem->content;
        }

        $this->json(array("trackId" => $trackId, "dateAdd" => $dateAdd, "operator" => $operator, "content" => $content, "shipId" => $shipId, "money" => $money));
    }

    protected function getReChangeItem($orderId, $operateType) {
        $arrReChange = array();
        $reChangeItem = Application_Model_Tracking::getOneByObjectTypeIdOperateType(Application_Model_DomainobjectType::ObjectType_Order, $orderId, $operateType);
        if ($reChangeItem) {
            $arrReChange["trackId"] = $reChangeItem->id;
            $arrReChange["dateAdd"] = $reChangeItem->dateAdd;
            $arrReChange["operator"] = $reChangeItem->operator;
            $arrReChange["content"] = $reChangeItem->content;
            $arrReChange["shipName"] = $reChangeItem->ShipItem ? $reChangeItem->ShipItem->Name : 0;
        }
        return $arrReChange;
    }

    /**
     * 添加异常处理步骤
     */
    public function addabnormalAction() {
        $orderId = $this->getSafeParam("id");
        $cause = $this->getSafeParam("cause");
        $abnormalId = $this->getSafeParam("abnormalId");
        $abnormalType = $this->getSafeParam("abnormalType");
        $abnormalScheme = $this->getSafeParam("abnormalScheme");
        $orderItem = Application_Model_Order::load($orderId);
        $operator = Uuch_Util::getUserNikeName();

        if (!$orderItem) {
            $this->json(array("type" => 0));
            return;
        }
        $abnormalItem = Application_Model_QualityProblemContent::load($abnormalId);
        if (!$abnormalItem) {
            $this->json(array("type" => 0));
            return;
        }

        if ($cause == "") {
            $this->json(array("type" => 2));
            return;
        }
        if (Application_Model_QualityProblemContent::Status_Default == $abnormalType) {
            Application_Model_Tracking::addTrack($abnormalItem->QualityProblem->ObjectType, $abnormalId, $operator, $cause, Application_Model_Tracking::User_Block, Application_Model_Tracking::Type_Quality, date("Y-m-d H:i:s"));
            $this->json(array("type" => 1, "dateCreated" => date("Y-m-d H:i:s"), "cause" => $cause, "operator" => $operator));
            return;
        }
        if ($abnormalScheme == Application_Model_Order::Scheme_Return || $abnormalScheme == Application_Model_Order::Scheme_Change) {
            $orderItem->rechangeStatus = Application_Model_Order::ReChange_Dispose;
            /**
             * 如果地址已经存在，则标志待悠奇发出
             */
            $track = Application_Model_Tracking::getOneByObjectTypeIdOperateType(Application_Model_DomainobjectType::ObjectType_Order, $orderId, Application_Model_Tracking::Type_Address);
            if ($track) {
                $orderItem->rechangeStatus = Application_Model_Order::ReChange_Emit;
            }
        } else if ($abnormalScheme == Application_Model_Order::Scheme_Reissue || $abnormalScheme == Application_Model_Order::Scheme_ReturnMoney) {
            $orderItem->rechangeStatus = Application_Model_Order::ReChange_Seller;
        } else if ($abnormalScheme != Application_Model_Order::Scheme_Renormal) {
            $this->json(array("type" => 0));
            return;
        }
        if ($abnormalType == Application_Model_QualityProblemContent::Status_Complated && $abnormalScheme != Application_Model_Order::Scheme_Renormal) {
            $orderItem->Scheme = $abnormalScheme;
        }

        $orderItem->save();

        Application_Model_Tracking::addTrack($abnormalItem->QualityProblem->ObjectType, $abnormalId, $operator, $cause, Application_Model_Tracking::User_Block, Application_Model_Tracking::Type_Quality, date("Y-m-d H:i:s"));
        if ($abnormalType == Application_Model_QualityProblemContent::Status_Complated) {
            $abnormalItem->status = Application_Model_QualityProblemContent::Status_Complated;
            $abnormalItem->save();
            $orderItem->addProblem($cause); 
            $this->solveOrderAbnormal($orderItem, $abnormalScheme);
        }
        $this->json(array("type" => 1, "dateCreated" => date("Y-m-d H:i:s"), "cause" => $cause, "operator" => $operator));
    }

    /**
     *  异常解决
     */
    protected function solveOrderAbnormal($orderItem, $abnormalScheme) {
        $orderProblem = Application_Model_QualityProblem::byObjectIdObjectType($orderItem->Id, Application_Model_DomainobjectType::ObjectType_Order);
        if ($orderProblem) {
            foreach ($orderProblem->getQualityProblemAll() as $qualityProbleVal) {
                if ($qualityProbleVal->status == Application_Model_QualityProblemContent::Status_Default) {
                    return false;
                }
            }
        }
        foreach ($orderItem->getItems() as $itemVal) {
            $ifSolve = $this->solveItemAbnormal($itemVal, $abnormalScheme);
            if (!$ifSolve) {
                return false;
            }
        }
        $orderItem->ckPass = 0;
        $orderItem->DateConfrim = date("Y-m-d H:i:s");
        $orderItem->isAbnormal = Application_Model_Order::Abnormal_Solve;
        if ($abnormalScheme == Application_Model_Order::Scheme_Renormal) {
            $orderItem->Scheme = '';
            $orderItem->rechangeStatus = '';
        }
        $orderItem->save();
        return true;
    }

    protected function solveItemAbnormal($itemVal, $abnormalScheme) {
        $ItemProblem = Application_Model_QualityProblem::byObjectIdObjectType($itemVal->Id, Application_Model_DomainobjectType::ObjectType_OrderItem);
        if ($ItemProblem) {
            foreach ($ItemProblem->getQualityProblemAll() as $qualityProbleVal) {
                if ($qualityProbleVal->status == Application_Model_QualityProblemContent::Status_Default) {
                    return false;
                }
            }
        }
        $itemVal->ckPass = 0;
        if ($abnormalScheme == Application_Model_Order::Scheme_Renormal) {
            $itemVal->status = '';
        }
        $itemVal->save();
        return true;
    }

    /**
     *  添加操作日志
     */
    public function addtracklogAction() {
        $id = $this->getSafeParam("id");
        $addLogTime = $this->getSafeParam("addLogTime");
        $addLogContent = $this->getSafeParam("addLogContent");
        $logIsVisible = $this->getSafeParam("logIsVisible");
        if ($addLogTime == "" || $addLogContent == "") {
            $this->json(2);
            return;
        }
        $orderItem = Application_Model_Order::load($id);
        if (!$orderItem) {
            $this->json(0);
            return;
        }
        $operator = Uuch_Util::getUserNikeName();
        $orderItem->dateConfrim = date("Y-m-d H:i:s");
        $orderItem->save();
        Application_Model_Tracking::addTrack(Application_Model_DomainobjectType::ObjectType_Order, $orderItem->id, $operator, $addLogContent, $logIsVisible, "", $addLogTime);
        $this->json(1);
    }

    /**
     *  获取异常代购的下单信息
     */
    public function lossshowAction() {
        $id = $this->getSafeParam("id");
        $orderItem = Application_Model_Order::load($id);
        if (!$orderItem) {
            $this->json(array("type" => 0));
            return;
        }
        $lossUser = "";
        $trackItem = Application_Model_Tracking::getOneByObjectTypeIdOperateType(Application_Model_DomainobjectType::ObjectType_Order, $id, Application_Model_Order::STATUS_UNSEND);
        if ($trackItem) {
            $lossUser = $trackItem->operator;
        }
        $this->json(array("type" => 1, "lossMoney" => $orderItem->Sum, "lossUser" => $lossUser));
    }

    /**
     *  记录错误代购损耗
     */
    public function sublossAction() {
        $id = $this->getSafeParam("id");
        $lossUser = $this->getSafeParam("lossUser");
        $lossMoney = $this->getSafeParam("lossMoney");
        $lossReason = $this->getSafeParam("lossReason");
        $orderItem = Application_Model_Order::load($id);
        if (!$orderItem) {
            $this->json(0);
            return;
        }
        if ($lossUser == "" || $lossMoney == "" || $lossReason == "") {
            $this->json(2);
            return;
        }
        Application_Model_FinancialCheckItem::addCheckItem(Application_Model_DomainobjectType::ObjectType_Order, $orderItem->Id, $lossMoney, $lossReason, $lossUser, $orderItem->UserId, Application_Model_FinancialCheckItem::Money_Loss);
        $this->json(1);
    }

    public function reissueorderAction() {
        $orderId = $this->getSafeParam("orderId");
        $reissueLogistics = $this->getSafeParam("reissueLogistics");
        $reissueLogisticsNo = $this->getSafeParam("reissueLogisticsNo");
        $orderItem = Application_Model_Order::load($orderId);
        if (!$orderItem) {
            $this->json(0);
            return;
        }
        if ($reissueLogisticsNo == "") {
            $this->json(2);
            return;
        }
        $operator = Uuch_Util::getUserNikeName();
        $track = Application_Model_Tracking::getOneByObjectTypeIdOperateType(Application_Model_DomainobjectType::ObjectType_Order, $orderId, Application_Model_Tracking::Type_ReissueLogistics);
        if (!$track) {
            Application_Model_Tracking::addTrack(Application_Model_DomainobjectType::ObjectType_Order, $orderId, $operator, $reissueLogisticsNo, Application_Model_Tracking::User_None, Application_Model_Tracking::Type_ReissueLogistics, date("Y-m-d H:i:s"), $reissueLogistics);
        } else {
            $track->content = $reissueLogisticsNo;
            $track->save();
        }

        $orderItem->rechangeStatus = Application_Model_Order::ReChange_Reissue;
        $orderItem->save();
        $this->json(1);
        return;
    }

    public function addrechangeaddressAction() {
        $orderId = $this->getSafeParam("orderId");
        $addressReturnChange = $this->getSafeParam("addressReturnChange");
        $qualityId = $this->getSafeParam("qualityId");
        $orderItem = Application_Model_Order::load($orderId);
        if (!$orderItem) {
            $this->json(0);
            return;
        }
        if ($addressReturnChange == "") {
            $this->json(2);
            return;
        }
        $qualityItem = false;
        if ($qualityId) {
            $qualityItem = Application_Model_Tracking::load($qualityId);
        }
        if ($qualityItem) {
            $qualityItem->content = $addressReturnChange;
            $qualityItem->save();
        } else {
            $operator = Uuch_Util::getUserNikeName();
            Application_Model_Tracking::addTrack(Application_Model_DomainobjectType::ObjectType_Order, $orderId, $operator, $addressReturnChange, Application_Model_Tracking::User_None, Application_Model_Tracking::Type_Address, date("Y-m-d H:i:s"));
            $orderItem->rechangeStatus = Application_Model_Order::ReChange_Emit;
            $orderItem->save();
        }
        $this->json(1);
        return;
    }

    public function addrechangelogisticsAction() {
        $orderId = $this->getSafeParam("orderId");
        $reChangeLogistics = $this->getSafeParam("reChangeLogistics");
        $reChangeLogisticsNo = $this->getSafeParam("reChangeLogisticsNo");
        $reChangeLogisticsMoney = $this->getSafeParam("reChangeLogisticsMoney");
        $qualityId = $this->getSafeParam("qualityId");
        $orderItem = Application_Model_Order::load($orderId);
        if (!$orderItem) {
            $this->json(0);
            return;
        }
        if ($reChangeLogisticsNo == "") {
            $this->json(2);
            return;
        }
        if ($reChangeLogisticsMoney == "" || $reChangeLogisticsMoney == 0) {
            $this->json(2);
            return;
        }
        $qualityItem = false;
        if ($qualityId) {
            $qualityItem = Application_Model_Tracking::load($qualityId);
        }
        if ($qualityItem) {
            $qualityItem->content = $reChangeLogisticsNo;
            $qualityItem->shipId = $reChangeLogistics;
            $qualityItem->save();
            $reChangeItem = Application_Model_Tracking::getOneByObjectTypeIdOperateType(Application_Model_DomainobjectType::ObjectType_Order, $qualityItem->objectId, Application_Model_Tracking::Type_ReChangeMoney);
            if ($reChangeItem) {
                $reChangeItem->content = $reChangeLogisticsMoney;
                $reChangeItem->save();
            }
        } else {
            $operator = Uuch_Util::getUserNikeName();
            Application_Model_Tracking::addTrack(Application_Model_DomainobjectType::ObjectType_Order, $orderId, $operator, $reChangeLogisticsNo, Application_Model_Tracking::User_None, Application_Model_Tracking::Type_ReChangeLogistics, date("Y-m-d H:i:s"), $reChangeLogistics);
            Application_Model_Tracking::addTrack(Application_Model_DomainobjectType::ObjectType_Order, $orderId, $operator, $reChangeLogisticsMoney, Application_Model_Tracking::User_None, Application_Model_Tracking::Type_ReChangeMoney, date("Y-m-d H:i:s"));
        }
        $orderItem->rechangeStatus = Application_Model_Order::ReChange_Seller;
        $orderItem->save();
        $this->json(1);
        return;
    }

    public function addreissuelogisticsAction() {
        $orderId = $this->getSafeParam("orderId");
        $orderReissueLogistics = $this->getSafeParam("orderReissueLogistics");
        $orderReissueLogisticsNo = $this->getSafeParam("orderReissueLogisticsNo");
        $qualityId = $this->getSafeParam("qualityId");
        $orderItem = Application_Model_Order::load($orderId);
        if (!$orderItem) {
            $this->json(0);
            return;
        }
        if ($orderReissueLogisticsNo == "") {
            $this->json(2);
            return;
        }
        $qualityItem = null;
        if ($qualityId) {
            $qualityItem = Application_Model_Tracking::load($qualityId);
        }
        if ($qualityItem) {
            $qualityItem->content = $orderReissueLogisticsNo;
            $qualityItem->shipId = $orderReissueLogistics;
            $qualityItem->save();
        } else {
            $operator = Uuch_Util::getUserNikeName();
            Application_Model_Tracking::addTrack(Application_Model_DomainobjectType::ObjectType_Order, $orderId, $operator, $orderReissueLogisticsNo, Application_Model_Tracking::User_None, Application_Model_Tracking::Type_ReissueLogistics, date("Y-m-d H:i:s"), $orderReissueLogistics);
            $orderItem->rechangeStatus = Application_Model_Order::ReChange_Reissue;
            $orderItem->save();
        }
        $this->json(1);
        return;
    }

    public function addrechangemoneyAction() {
        $orderId = $this->getSafeParam("orderId");
        $reChangeMoney = $this->getSafeParam("reChangeMoney");
        $orderItem = Application_Model_Order::load($orderId);
        if (!$orderItem) {
            $this->json(0);
            return;
        }
        if ($reChangeMoney == "" && $reChangeMoney <= 0) {
            $this->json(2);
            return;
        }
        $operator = Uuch_Util::getUserNikeName();
        Application_Model_Tracking::addTrack(Application_Model_DomainobjectType::ObjectType_Order, $orderId, $operator, $reChangeMoney, Application_Model_Tracking::User_None, Application_Model_Tracking::Type_ReturnMoney, date("Y-m-d H:i:s"));
        $orderItem->rechangeStatus = Application_Model_Order::ReChange_Complete;
        $orderItem->save();

        $accountObj = Application_Model_UserAccount::load($orderItem->userId);
        $beforeMoney = $accountObj->Money;
        $title = "异常代购：" . $orderItem->OrderNum . "为您退款" . $reChangeMoney . "元";
        Application_Model_Tracking::addTrack(Application_Model_DomainobjectType::ObjectType_Order, $orderId, $operator, $title, Application_Model_Tracking::User_Block, "", date("Y-m-d H:i:s"));

        $accountObj->money = $accountObj->money + $reChangeMoney;
        $afterMoney = $beforeMoney + $reChangeMoney;

        $accountObj->save();

        $userAccountHistory = new Application_Model_UserAccountHistory();
        $userAccountHistory->type = Application_Model_UserAccountHistory::TYPE_MANU;
        $userAccountHistory->beforeMoney = $beforeMoney;
        $userAccountHistory->afterMoney = $afterMoney;
        $userAccountHistory->comment = $title;
        $userAccountHistory->dateCreated = date('Y-m-d H:i:s', time());
        $userAccountHistory->relaseId = $orderId;
        $userAccountHistory->accountId = $orderItem->userId;
        $userAccountHistory->State = Application_Model_UserAccountHistory::STATE_MONEY;
        $userAccountHistory->save();
        $messageItem = new Application_Model_Mail();
        $messageItem->title = "尊敬的客户，您好！" . $title;
        $messageItem->userId = $orderItem->userId;
        $messageItem->type = 2;
        $messageItem->status = Application_Model_Mail::UNREAD;
        $messageItem->message = "尊敬的客户，您好！因您的代购订单(" . $orderItem->getOrderNum() . ")出现异常，协商为您退款" . $reChangeMoney . "元。";
        $messageItem->dateCreated = date("Y-m-d H:i:s");
        $messageItem->save();
        if (0 < $reChangeMoney) {
            $data = array('beforeMoney' => $beforeMoney, 'account' => $accountObj, 'afterMoney' => $beforeMoney + $reChangeMoney, 'businessType' => "spjztk");
            $data['trader'] = 'account-number-dr';
            $this->_addFinance($orderItem, $reChangeMoney, $data);
            $data['trader'] = 'backend-account-cr';
            $data['beforeMoney'] = $data['afterMoney'];
            $this->_addFinance($orderItem, $reChangeMoney, $data);
        }
        $this->json(1);
        return;
    }

    public function setschemecompleteAction() {
        $id = (int) $this->getSafeParam('id');
        if ($id) {
            $order = Application_Model_Order::load($id);
            if ($order) {
                $order->rechangeStatus = Application_Model_Order::ReChange_Complete;
                $order->status = Application_Model_Order::STATUS_INSTORE;
                $order->save();
                $this->json(1);
            } else {
                $this->json(0);
            }
        } else {
            $this->json(0);
        }
    }

    public function reprevestepAction() {
        $id = (int) $this->getSafeParam('id');
        $rel = $this->getSafeParam('rel');
        $orderItem = Application_Model_Order::load($id);
        $orderItem->rechangeStatus = '';
        $orderItem->scheme = Application_Model_Order::Scheme_Reprocess;
        $orderItem->save();
        if (is_numeric($rel)) {
            $problemContent = Application_Model_QualityProblemContent::load($rel);
            $problemContent->status = Application_Model_QualityProblemContent::Status_Default;
            $problemContent->save();
        }

        $this->json(1);
    }

    protected function _addFinance($order, $money, $params) {


        require_once(APPLICATION_PATH . '/../library/finance/General.php');
        $trade = isset($params['trader']) ? $params['trader'] : 'backend-account-dr';
        $remark = isset($params['remark']) ? $params['remark'] : '';
        $account = $params['account'];
        $user = Application_Model_User::load($order->userId);
        $data = array(
            'transaction_number' => '',
            'trader' => $trade,
            'customer_id' => $order->userId,
            'member' => 'admin',
            'amount' => $money,
            'customer_name' => $user->nikename,
            'currency' => 'CNY',
            'rate' => '1',
            'rate_amount' => '0',
            'period_start' => $params['beforeMoney'],
            'period_end' => $params['afterMoney'],
            'business_type' => $params['businessType'],
            'order_sn' => $order->OrderNum,
            'remark' => $remark,
            'created_at' => date('Y-m-d H:i:s')
        );
        try {
            $api = new General($params['beforeMoney'], $account);
            $api->setFields($data);
            $api->addTransaction();
            $result = array('code' => 'success', 'message' => '');
        } catch (Exception $ex) {
            echo $ex->getMessage();
            $result = array('code' => 'error', 'message' => $ex->getMessage());
        }
    }

}
